package org.jeecg.modules.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.RedisCacheConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.FileUploadUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.business.mapper.ServiceTaskMapper;
import org.jeecg.modules.business.service.IServiceTaskService;
import org.jeecg.modules.manage.entity.CaishuiServiceTask;
import org.jeecg.wx.utils.WxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @Description: 服务任务
 * @Author: yfkj
 * @Date:   2023-01-05
 * @Version: V1.0
 */
@Service
public class ServiceTaskServiceImpl extends ServiceImpl<ServiceTaskMapper, CaishuiServiceTask> implements IServiceTaskService {

    @Autowired
    private RedisUtil redisUtil;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;//文件上传根目录


    /**
     * 生成任务
     * @param caishuiServiceTask
     */
    @Override
    @Transactional
    public void saveTask(CaishuiServiceTask caishuiServiceTask) {
        this.baseMapper.insert(caishuiServiceTask);
        //生成小程序二维码
        Result<?> result = createQRCode(caishuiServiceTask.getBusinessId(), caishuiServiceTask.getId());
        if (!result.isSuccess()) throw new JeecgBootException(result.getMessage());
        //更新任务微信小程序码
        caishuiServiceTask.setInvitationCodeWx(result.getResult().toString());
        this.baseMapper.updateById(caishuiServiceTask);
    }

    /**
     * 根据任务ID生成小程序码
     * @param id
     * @return
     */
    public Result<?> createQRCode(String businessId, String id) {
        if (oConvertUtils.isEmpty(businessId) || oConvertUtils.isEmpty(id)) return Result.error("参数不能为空！");
        try {
            //先从缓存获取AccessToken
            String tokenCache = oConvertUtils.getString(redisUtil.get(RedisCacheConstant.wx_access_token_cache),null);
            if (oConvertUtils.isEmpty(tokenCache)){
                //发送请求获取微信小程序TOKEN
                tokenCache = WxUtil.getAccessTokenAsUrl();
                if (oConvertUtils.isEmpty(tokenCache)) return Result.error("获取token失败！");
                //保存TOKEN到redis缓存
                redisUtil.set(RedisCacheConstant.wx_access_token_cache, tokenCache, 3600);
            }

            //下载带参数的小程序二维码到本地
            String bizPath = "uploadImg/business/task/" + businessId + "/" + id + ".png";
            String path = upLoadPath + "/" + bizPath;
            boolean bool = WxUtil.downloadMiniCode(tokenCache,upLoadPath + "/" + bizPath,id,"signingPages/taskdetails");
            if (!bool) return Result.error("获取二维码失败！");

            //上传二维码到服务器
            String savePath = FileUploadUtil.fileUpload(path, bizPath);
            if(oConvertUtils.isEmpty(savePath)){
                return Result.error("上传二维码错误！");
            }
            return Result.OK("请求成功！",savePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("请求失败！");
    }

    /**
     * 获取固定签约服务类型列表
     * @return
     */
    @Override
    public List<Map<String,Object>> getSigningServiceList(){
        return this.baseMapper.getSigningServiceList();
    };

    /**
     * 根据ID获取非固定签约服务类型列表
     * @return
     */
    @Override
    public List<Map<String,Object>> getSigningServiceListByIDs(String ids){
        return this.baseMapper.getSigningServiceListByIDs(ids);
    };
}
